﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

using SJTU.SE.RoughSet.Lib.Data;

namespace SJTU.SE.RoughSet.Lib.Reduct
{
    public class Reductor
    {
        private DecisionTable mTarget;
        private List<int> mSkowronCore = new List<int>();
        private List<int>[,] mDiscernibilityMatrix;
        private bool mHasDiscernibilityMatrix = false;
        private List<List<int>> mReductions;

        private Tuple<List<int>, int>[,] mDiscernibilityMatrix2;

        public DecisionTable TargetDecisionTable
        {
            get
            {
                return this.mTarget;
            }
        }

        public Reductor(DecisionTable targeDecisionTable)
        {
            this.mTarget = targeDecisionTable;
            this.mDiscernibilityMatrix = new List<int>[mTarget.ElementCount, mTarget.ElementCount];
            this.mReductions = new List<List<int>>();

            this.mDiscernibilityMatrix2 = new Tuple<List<int>, int>[mTarget.ElementCount, mTarget.ElementCount];
        }

        #region Skowron Discernibility Matrix

        /// <summary>
        /// 基于Skowron差异矩阵的决策表属性约简，求core
        /// 只能处理相容决策表
        /// </summary>
        /// <returns></returns>
        public List<int> GetSkowronCore()
        {
            if (this.mSkowronCore.Count != 0)
            {
                return this.mSkowronCore;
            }
            else
            {
                List<int> temp = new List<int>();

                //循环下三角差异矩阵
                for (int i = 0; i < this.mTarget.ElementCount; i++)
                {
                    for (int j = 0; j < i; j++)
                    {
                        //decision 不同
                        if (mTarget.Decisions[j] != mTarget.Decisions[i])
                        {
                            //差异属性
                            for (int t = 0; t < mTarget.SymptonCount; t++)
                            {
                                if (mTarget[i, t] != mTarget[j, t])
                                {
                                    temp.Add(t);
                                }
                            }

                            //所有属性相同而decision不同，决策表不相容
                            if (temp.Count == 0)
                            {
                                throw new Exception("Inconsistent decision table");
                            }

                            //单一差异属性
                            if (temp.Count == 1)
                            {
                                if (!mSkowronCore.Contains(temp[0]))
                                {
                                    mSkowronCore.Add(temp[0]);
                                }
                            }
                            mDiscernibilityMatrix[i, j] = temp.ToList();
                            //clean up temp data
                            temp.Clear();
                        }
                    }
                }
                this.mHasDiscernibilityMatrix = true;
                return mSkowronCore;
            }
        }

        public bool IsReduction(List<int> reduction)
        {
            if (!this.mHasDiscernibilityMatrix)
            {
                this.GetSkowronCore();
            }
            //check core first
            //should contians all core elements
            foreach (var core in this.mSkowronCore)
            {
                if (!reduction.Contains(core))
                {
                    return false;
                }
            }
            bool isFound = false;
            foreach (var diff in mDiscernibilityMatrix)
            {
                if (diff != null)
                {
                    foreach (var a in diff)
                    {
                        if (reduction.Contains(a))
                        {
                            isFound = true;
                            break;
                        }
                    }
                    if (!isFound)
                    {
                        return false;
                    }
                    else

                        isFound = false;
                }
            }
            return true;
        }

        public List<List<int>> GetAllReductionsByTraversal()
        {
            if (this.mHasDiscernibilityMatrix)
            {
                this.GetSkowronCore();
            }

            List<int> attributes = new List<int>();
            for (int i = 0; i < mTarget.SymptonCount; i++)
            {
                if (!this.mSkowronCore.Contains(i))
                    attributes.Add(i);
            }
            //广度优先遍历
            //GetAllReductionByTraversal(this.mSkowronCore, attributes);
            Queue<List<int>> reductionsToTest = new Queue<List<int>>();
            //core 加入队列
            reductionsToTest.Enqueue(this.mSkowronCore);
            bool independence = true;
            while (reductionsToTest.Count > 0)
            {
                independence = true;
                var tempReduction = reductionsToTest.Dequeue();
                foreach (var reduction in this.mReductions)
                {
                    if (reduction.All(a => tempReduction.Contains(a)))
                    {
                        independence = false;
                        break;
                    }
                }
                if (independence && IsReduction(tempReduction))
                {
                    //如果是reduction 则加入list，此分支结束
                    this.mReductions.Add(tempReduction);
                }
                else
                {
                    int last = this.mSkowronCore.Contains(tempReduction.Last()) ? -1 : tempReduction.Last();

                    foreach (var i in attributes.Where(a => a > last))
                    {
                        var temp = tempReduction.ToList();
                        temp.Add(i);
                        reductionsToTest.Enqueue(temp);
                    }
                }
            }
            return this.mReductions;            
        }

        public void GetDiscernibilityMatrix()
        {
            int m_martrix = 0;

            bool[] elementStates = new bool[this.mTarget.ElementCount];
            for (int i = 0; i < this.mTarget.ElementCount; i++)
            {
                elementStates[i] = true;
            }

            List<int> temp = new List<int>();
            int tag = 0;
            bool addMatrix = false;

            for (int i = 1; i < this.mTarget.ElementCount; i++)
            {
                addMatrix = false;
                mDiscernibilityMatrix2[m_martrix, m_martrix] = new Tuple<List<int>, int>(null, 0);

                for (int m = 0; m < i; m++)
                {
                    //差异属性
                    for (int t = 0; t < mTarget.SymptonCount; t++)
                    {
                        if (mTarget[i, t] != mTarget[m, t])
                        {
                            temp.Add(t);
                        }
                    }

                    if (temp.Count == 0)
                    {

                        if (mTarget.Decisions[i] != mTarget.Decisions[m])
                        {
                            tag = 2;
                            elementStates[m] = false;

                            //
                            for (int x = 0; x < this.mTarget.ElementCount; x++)
                            {
                                if (mDiscernibilityMatrix2[x, m] != null)
                                {
                                    if( mDiscernibilityMatrix2[x, m].Item2 == 0 || mDiscernibilityMatrix2[x, m].Item2 == 1)
                                    {
                                        mDiscernibilityMatrix2[x, m] = new Tuple<List<int>,int>( mDiscernibilityMatrix2[x, m].Item1,2);
                                    }
                                    if (mDiscernibilityMatrix2[x, m].Item2 == 2)
                                    {
                                        mDiscernibilityMatrix2[x, m] = new Tuple<List<int>, int>(mDiscernibilityMatrix2[x, m].Item1, 3);
                                    }
                                }
                            }

                        }                       
                    }
                    else
                    {
                        if (elementStates[m] == true)
                        {
                            if (mTarget.Decisions[i] != mTarget.Decisions[m])
                            {
                                tag = 1;
                            }
                            else
                            {
                                tag = 0;
                            }
                        }
                        else
                        {
                            tag = 2;
                        }

                        mDiscernibilityMatrix2[m_martrix, m] = new Tuple<List<int>, int>(temp.ToList(), tag);
                        addMatrix = true; ;
                    }
                    temp.Clear();
                }
                if (addMatrix)
                {
                    m_martrix++;
                }

            }

            for (int p = 0; p < this.mTarget.ElementCount; p++)
            {
                for (int q = 0; q < this.mTarget.ElementCount; q++)
                {
                    if (mDiscernibilityMatrix2[p, q] != null)
                    {
                        if (mDiscernibilityMatrix2[p, q].Item2 == 3)
                        {
                            mDiscernibilityMatrix2[p, q] = null;
                        }
                    }

                    mDiscernibilityMatrix[p, q] = mDiscernibilityMatrix2[p, q]==null?null:mDiscernibilityMatrix2[p, q].Item1;

                }
            }

            mHasDiscernibilityMatrix = true;

        }

        /*
        public List<List<int>> GetAllReductionByIndiscernibilityFunction()
        {
            if (!this.mHasSkowronCore)
            {
                this.GetSkowronCore();
            }

            List<List<int>> Indiscernibility = new List<List<int>>();
            for (int i = 0; i < this.mTarget.ElementCount; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    if (this.mDiscernibilityMatrix[i, j] != null && this.mDiscernibilityMatrix[i, j].Count > 1 
                        && !this.mSkowronCore.Any(a=>this.mDiscernibilityMatrix[i,j].Contains(a)))
                    {
                        bool isNew = true;
                        for (int m = 0; m < Indiscernibility.Count; m++)
                        {
                            if (Indiscernibility[m].Count >= this.mDiscernibilityMatrix[i, j].Count && this.mDiscernibilityMatrix[i, j].All(a => Indiscernibility[m].Contains(a)))
                            {
                                if (isNew)
                                {
                                    Indiscernibility[m] = this.mDiscernibilityMatrix[i, j];
                                }
                                else
                                {
                                    Indiscernibility.RemoveAt(m);                                    
                                }
                                isNew = false;
                                continue;                                
                            }
                            else if (Indiscernibility[m].Count < this.mDiscernibilityMatrix[i, j].Count && Indiscernibility[m].All(a => this.mDiscernibilityMatrix[i, j].Contains(a)))
                            {
                                isNew = false;
                                break;
                            }
                        }
                        if(isNew)
                            Indiscernibility.Add(this.mDiscernibilityMatrix[i, j]);
                    }

                }
            }
            return Indiscernibility;
        }

        private List<List<int>> GetAllReductionByIndiscernibilityFunction(List<List<int>> currentReduction, List<List<int>> left)
        {
            if(left.Count > 0)
            {
                var current = left[0];
                left.RemoveAt(0);
                int first = current[0];
                foreach (var i in currentReduction)
                {
                    if (!i.Contains(first))
                    {
                        i.Add(first);
                        i.Sort();
                    }
                }
                
                foreach (var i in current)
                {

                }

            }
            
        }*/
       

        #endregion
    }
}
